package com.tool.weixin.api;


import java.util.UUID;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import com.tool.weixin.cache.WeixinCacheManager;
import com.tool.weixin.model.JsApiTicket;
import com.tool.weixin.model.Signature;
import com.tool.weixin.util.HttpUtils;
import com.tool.weixin.util.SignUtil;

public class JsApi {
	
	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(JsApi.class);
	
	/**
	 * 获取jsapi_ticket
	 */
	private static final String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
	
	public static String getJsapiTicket() {
		String ticket = WeixinCacheManager.getInstance().getJsapiTicket();
		if(StringUtils.isNotEmpty(ticket)) return ticket;
        String requestUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", AccessTokenApi.getAccessToken().getToken());
        JSONObject jsonObject =HttpUtils.httpRequest(requestUrl, "GET", null);
        
        if (null != jsonObject) {
            try {
            	JsApiTicket jsApiTicket = new JsApiTicket();
            	jsApiTicket.setExpiresIn(jsonObject.getInt("expires_in"));
            	jsApiTicket.setTicket(jsonObject.getString("ticket"));
                ticket = jsApiTicket.getTicket();
                WeixinCacheManager.getInstance().saveJsapiTicket(jsApiTicket);
            } catch (Exception e) {
                logger.error("获取JsapiTicket失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return ticket;
    }

	/**
	 * 获取js-sdk所需的签名，简化逻辑
	 * @author huff
	 * @date 2016年5月27日
	 * @param url
	 * @param appid
	 * @param appsecret
	 * @return
	 */
	public static Signature getSignature(String url,String appid, String appsecret) {
		String timestamp = String.valueOf(System.currentTimeMillis()/1000);
		String noncestr = UUID.randomUUID().toString().replaceAll("-", "");
		return getSignature(url, noncestr, timestamp, appid,appsecret);
	}
	/**
	 * 获取js-sdk所需的签名
	 * @author huff
	 * @date 2016年5月27日
	 * @param url
	 * @param noncestr 随机字符串
	 * @param timestamp 时间戳
	 * @param appid
	 * @param appsecret
	 * @return
	 */
	public static Signature getSignature(String url,String noncestr,String timestamp,String appid, String appsecret) {
		String jsapi_ticket = getJsapiTicket();
		String sign = SignUtil.getSignature(jsapi_ticket, noncestr, timestamp, url);
		Signature signature = new Signature();
		signature.setNoncestr(noncestr);
		signature.setSignature(sign);
		signature.setTimestamp(timestamp);
		signature.setAppid(appid);
		return signature;
	}
}
